package normalObjects;

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

/**
 * @author 26029
 * @date 2025/4/8
 * @description
 */
public class LearnHashCode {
    int x, y;

    LearnHashCode(int x, int y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public boolean equals(Object object) {
        if (this == object) return true;
        if (object == null || getClass() != object.getClass()) return false;
        LearnHashCode that = (LearnHashCode) object;
        return x == that.x && y == that.y;
    }

    @Override
    public int hashCode() {
        // return Objects.hash(x, y);
        return x + y;
    }

    @Override
    public String toString() {
        return "LearnHashCode{" + "x=" + x + ", y=" + y + '}';
    }

    public static void main(String[] args) {
        // o1,o2虽然是不同对象,但是hashCode相同且equals,故在hashset中能找到
        // o1,o3虽然hashCode相同,但是不equals,故在hashset中找不到
        LearnHashCode o1 = new LearnHashCode(1, 2);
        LearnHashCode o2 = new LearnHashCode(1, 2);
        LearnHashCode o3 = new LearnHashCode(2, 1);
        Set<LearnHashCode> set = new HashSet<>();
        set.add(o1);
        System.out.println("o1:" + o1);
        System.out.println("o2:" + o2);
        System.out.println("o3:" + o3);
        System.out.println("添加o1");
        System.out.println(set.contains(o2) ? "存在o2" : "不存在o2");
        System.out.println(set.contains(o3) ? "存在o3" : "不存在o3");
    }
}
